package cn.dansj.controller;

import cn.dansj.common.request.annotation.http.GetMethod;
import cn.dansj.common.request.annotation.http.RequestMappingMethod;
import cn.dansj.common.request.annotation.http.RequestParam;
import cn.dansj.common.utils.json.DictMap;
import cn.dansj.entity.ShortLink;
import cn.dansj.common.utils.enums.BooleanType;
import cn.dansj.common.request.RequestUtils;
import cn.dansj.common.redis.RedisUtils;
import cn.dansj.common.utils.transfer.Transformation;
import cn.dansj.common.utils.transfer.Verification;
import cn.dansj.handler.interfaces.ShortLinkGenerate;
import jakarta.servlet.http.HttpServletResponse;

@RequestMappingMethod
public class ShortLinkController {
    private final RedisUtils redisUtils;

    public ShortLinkController(RedisUtils redisUtils) {
        this.redisUtils = redisUtils;
    }

    @GetMethod(value = "/short/{shortUrl}", permission = BooleanType.TRUE)
    public void redirect(@RequestParam(path = true) String shortUrl, HttpServletResponse response) {
        final long expire = redisUtils.getExpire(ShortLinkGenerate.key(shortUrl));
        final ShortLink shortlink = expire == -1 || expire > 0 ? DictMap.parseObject(redisUtils.hgetall(ShortLinkGenerate.key(shortUrl)), ShortLink.class) : null;

        if (Verification.checkNotNull(shortlink) && Verification.checkNotNull(shortlink.getUrl())) {
            response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
            final String url = shortlink.getUrl();
            response.setHeader("Location", Transformation.patternExist(url, "^(https?://)") ? url : "https://" + url);
        } else {
            RequestUtils.response404();
        }
    }
}
